#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>


int try_port(int sockfd,struct sockaddr * pserver_addr)
{
	/* 客户程序发起连接请求 */ 
	if(connect(sockfd,pserver_addr,sizeof(struct sockaddr))==-1) 
	{ 
		//fprintf(stderr,"Connect Error:%s\a\n",strerror(errno)); 
		return(-1); 
	} 
	

	return 1;
}

int main(int argc, char **argv)
{
	int sockfd;
	int ret;
	struct sockaddr_in server_addr; 
	unsigned short portnumber = 0;
	int i;
	int flag;	

	if(argc < 1)
	{
		fprintf(stderr,"Usage:%s ipaddr \a\n",argv[0]); 
		return -1;
	}

	for(i=1;i<65535;i++)
	{
	
		//printf("try port %d ...\n",i);
		/* 客户程序开始建立 sockfd描述符 */ 
		if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) // AF_INET:Internet;SOCK_STREAM:TCP
		{ 
			fprintf(stderr,"Socket Error:%s\a\n",strerror(errno)); 
			exit(1); 
		} 

		/* 客户程序填充服务端的资料 */ 
		bzero(&server_addr,sizeof(server_addr)); // 初始化,置0
		server_addr.sin_family=AF_INET;          // IPV4
		server_addr.sin_addr.s_addr=inet_addr(argv[1]); // IP地址
		server_addr.sin_port=htons(i);  // (将本机器上的short数据转化为网络上的short数据)端口号

		/*设置为非阻塞模式*/
		flag = fcntl(sockfd, F_GETFL, 0);
		flag |= O_NONBLOCK;
		fcntl(sockfd, F_SETFL, flag);
		
		ret = try_port(sockfd,(struct sockaddr *)(&server_addr));
		if(ret == 1)
		{
			printf("\t\tport %d can access\n",i);
		}
		
		close(sockfd); 
	}
	/* 结束通讯 */ 

	return 0;
}
